package com.github.netty.springboot;

import java.security.Security;

import javax.annotation.PostConstruct;
import javax.naming.NamingException;
import javax.naming.spi.NamingManager;

import org.springframework.context.annotation.Configuration;

/**
 * 禁用rmi、ldap、ldaps、javax.naming、jndi等远程调用协议，以防止远程执行任意命令
 */
@Configuration
class SecurityExtConfig {
	
	@PostConstruct
	private void init() {
		disableRMI();
		disableLDAPs();
		disableJNDI();
		setSecurityProperty();
	}
	
	//禁用RMI
	private void disableRMI() {
//		System.setProperty("java.rmi.server.hostname", "");
		System.setProperty("rmi.server.enable", "false");
		System.setProperty("java.rmi.server.useCodebaseOnly", "true");
		System.setProperty("java.rmi.server.disableHttp", "true");
		System.setProperty("com.sun.management.jmxremote", "false");
		System.setProperty("java.rmi.server.disableRegistry", "true");
//		if (System.getSecurityManager() == null) {
//		    System.setSecurityManager(new SecurityManager());
//		}
		String s = System.getProperty("sun.rmi.transport.tcp.maxConnections");
		if(s!=null) {
			System.setProperty("sun.rmi.transport.tcp.maxConnections","null");
		}
	}
	
	//禁用LDAP和LDAPS
	private void disableLDAPs() {
		System.setProperty("com.sun.jndi.ldap.object.trustURLCodebase", "false");
		System.setProperty("com.sun.jndi.rmi.object.trustURLCodebase", "false");
		System.setProperty("com.sun.jndi.dns.object.trustURLCodebase", "false");
		System.setProperty("com.sun.jndi.cosnaming.object.trustURLCodebase", "false");
		System.setProperty("com.sun.jndi.ldap.connect.pool.ssl", "false");
	}
	
	//禁用JNDI
	private void disableJNDI() {
		// 设置系统属性
		System.setProperty("com.sun.jndi.ldap.object.disableEndpointChecking", "false");
		System.setProperty("com.sun.jndi.rmi.object.disableAnonymousObject", "false");
		System.setProperty("java.naming.ldap.factory.socket", "com.github.netty.springboot.NoPermissionsInitialContextFactory");
		System.setProperty("java.naming.factory.initial", "com.github.netty.springboot.NoPermissionsInitialContextFactory");
		System.setProperty("org.apache.naming.java.javaURLContext.disableUrlLoading", "true");
		System.setProperty("cxfometimes.disablejdei", "true");
		try {
			NamingManager.setInitialContextFactoryBuilder(env -> new NoPermissionsInitialContextFactory());
		} catch (NamingException e) {
			e.printStackTrace();
		}
		Security.setProperty("jndi.initial.context.factory", "com.github.netty.springboot.NoPermissionsInitialContextFactory");
	}
	
	private void setSecurityProperty() {
//		# 禁止RMI URL加载
		Security.setProperty("secureremoteobject.allowLoadCodebaseProperty", "false");
//		# 禁止从URL加载对象
		Security.setProperty("secureremoteobject.codebasePrincipalSupport", "false");
//		# 禁止使用RMI注册中心
		Security.setProperty("secureregistry.disable", "true");
	}
	
	

}
